package com.kaifamiao.wendao.type;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.logging.Logger;

public class LocalDateTimeTypeHandler implements TypeHandler<LocalDateTime> {

    // Java原生日志 ( JUL: java.util.logging )
    private Logger logger = Logger.getLogger( this.getClass().getName() );

    @Override
    public void setParameter(PreparedStatement ps, int index, LocalDateTime datetime, JdbcType jdbcType) throws SQLException {
        if( datetime != null ) {
            logger.info( "设置timestamp取值" );
            Timestamp ts = Timestamp.valueOf( datetime );
            ps.setTimestamp(index, ts);
        }
    }

    @Override
    public LocalDateTime getResult(ResultSet rs, String label) throws SQLException {
        logger.info( "获取" + label + "列的值" );
        return convert( rs.getTimestamp( label ) );
    }

    @Override
    public LocalDateTime getResult(ResultSet rs, int index) throws SQLException {
        return convert( rs.getTimestamp( index ) );
    }

    @Override
    public LocalDateTime getResult(CallableStatement cs, int index) throws SQLException {
        return convert( cs.getTimestamp( index ) );
    }

    private LocalDateTime convert(Timestamp ts){
        if( ts != null ) {
            return ts.toLocalDateTime();
        }
        return null ;
    }
}
